package com.coding.mybatis;

import java.lang.reflect.Proxy;
import java.util.List;
import java.util.Objects;

/**
 * @ClassName DefaultSqlSession
 * @Author ykx
 * @Date 2023/12/31 17:34
 * @Version 1.0
 */
public class DefaultSqlSession implements SqlSession {

    private Configuration configuration;
    private Executor defaultExecutor = new DefaultExecutor();

    public DefaultSqlSession(Configuration configuration) {
        this.configuration = configuration;
    }

    @Override
    public <E> List<E> selectList(String statementId, Object... parameters) throws Exception {
        MappedStatement mappedStatement = configuration.getStatementMap().get(statementId);
        List<E> results = defaultExecutor.query(configuration, mappedStatement, parameters);
        return results;
    }

    @Override
    public <T> T selectOne(String statementId, Object... parameters) throws Exception {
        List<Object> objects = selectList(statementId, parameters);
        if (Objects.nonNull(objects) && objects.size() == 1) {
            return (T) objects.get(0);
        } else if (Objects.isNull(objects) || objects.size() == 0) {
            return null;
        } else {
            throw new RuntimeException("返回结果数目太多");
        }
    }

    @Override
    public void close() throws Exception {
        defaultExecutor.close();
    }

    @Override
    @SuppressWarnings("unchecked")
    public <T> T getMapper(Class<T> clazz) {
        MapperProxy mapperProxy = new MapperProxy(this, clazz, configuration);
        return (T) Proxy.newProxyInstance(clazz.getClassLoader(), new Class[]{clazz}, mapperProxy);
    }
}
